package org.example.mall4j.Handler;

import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.mall4j.Utils.IpUtil;
import org.example.mall4j.Utils.RedisCache;
import org.example.mall4j.Utils.TokenUtil;
import org.example.mall4j.common.LoginResultObject;
import org.example.mall4j.pojo.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 自定义认证成功处理器
 */
@Component("loginSuccessHandler")
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisCache redisCache;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        SysUser user = (SysUser)authentication.getPrincipal();
        // 登录成功处理
        System.out.println(IpUtil.getIpAddr());
        //1.生成token
        String token = TokenUtil.genAccessToken(user.getUsername());
        String name = TokenUtil.getUserFromToken(token);
        long expireTime = TokenUtil.getExpirationTime(token);
        // 配置一下返回给前端的token信息
        LoginResultObject vo = new LoginResultObject();
        // 将实体类信息转为JSON
        // TODO 将token存入coookie中 后面加载页面 根据用户的id取查询对应的权限

        vo.setUserInfo(user);
        vo.setCode(200L);

        // TODO 将token存放到redis中 退出或者修改密码 清空token 获取的时候 也从redis中进行获取
        redisCache.setCacheObject(IpUtil.getIpAddr(),token, TokenUtil.ACCESS_EXPIRE, TimeUnit.MILLISECONDS);
        vo.setToken(token);
        vo.setExpireTime(expireTime);

        String res = JSONObject.toJSONString(vo);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();
        out.write(res.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}

